package com.zz.tijian.utils;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.zz.tijian.expections.CommonException;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ValidationUtils {

    /**
     * 验证对象中所有字段是否为空
     *
     * @param obj 待验证的对象
     * @throws IllegalArgumentException 如果有字段为空，则抛出异常
     */
    public static void validate(Object obj) throws IllegalArgumentException {
        List<String> emptyFields = new ArrayList<>();
        Field[] fields = ReflectUtil.getFields(obj.getClass());

        for (Field field : fields) {
            field.setAccessible(true);
            Object value = ReflectUtil.getFieldValue(obj, field);
            if (value == null || (value instanceof String && StrUtil.isBlank((String) value))) {
                emptyFields.add(field.getName());
            }
        }

        if (!emptyFields.isEmpty()) {
            throw new CommonException("以下字段为空: " + String.join(", ", emptyFields));
        }
    }

    public static void main(String[] args) {
        // 测试示例
        class TestEntity {
            private String field1;
            private Integer field2;
            private String field3;

            public TestEntity(String field1, Integer field2, String field3) {
                this.field1 = field1;
                this.field2 = field2;
                this.field3 = field3;
            }
        }

        TestEntity entity = new TestEntity("test", null, " ");

        try {
            ValidationUtils.validate(entity);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}
